<template>
  <div class="design-editor-container">
    <div class="editor-layout">
      <!-- 左侧侧边栏 -->
      <div class="editor-sidebar">
        <design-sidebar 
          @add-element="handleAddElement"
          @toggle-grid="toggleGrid"
          @toggle-ruler="toggleRuler"
          @color-change="setColor"
          @add-material="addMaterial"
        />
      </div>
      
      <!-- 中间画布区域 -->
      <div class="editor-canvas-area">
        <div class="editor-toolbar">
          <div class="toolbar-left">
            <el-button-group>
              <el-button size="small" @click="copySelected">复制</el-button>
              <el-button size="small" @click="deleteSelected">删除</el-button>
              <el-button size="small" @click="moveToTop">移到顶部</el-button>
              <el-button size="small" @click="moveToBottom">移到底部</el-button>
            </el-button-group>
          </div>
          
          <div class="toolbar-right">
            <el-button size="small" type="primary" @click="saveDesign">保存</el-button>
            <el-button size="small" @click="exportDesign">导出</el-button>
            <el-button size="small" @click="previewDesign">预览</el-button>
          </div>
        </div>
        
        <div class="canvas-container">
          <canvas ref="fabricCanvas" class="fabric-canvas"></canvas>
        </div>
      </div>
      
      <!-- 右侧属性面板 -->
      <div class="editor-properties">
        <div class="properties-header">
          <h3>属性</h3>
        </div>
        
        <div v-if="selectedObject" class="properties-content">
          <design-property-panel
            :selected-object="selectedObject"
            @update-property="updateObjectProperty"
            @toggle-text-style="toggleTextStyle"
          />
        </div>
        
        <div v-else class="no-selection-hint">
          <p>请选择一个对象来编辑属性</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted, nextTick } from 'vue';
import * as fabric from "fabric";
import DesignSidebar from '@/modules/designer/components/sidebar/DesignSidebar.vue';
import DesignPropertyPanel from '@/modules/designer/components/property/PropertyPanel.vue';

// Canvas reference
const fabricCanvas = ref(null);
let canvas = null;

// 编辑器状态
const selectedColor = ref('#FF5722');
const selectedObject = ref(null);
const isTextObject = computed(() => {
  return selectedObject.value && selectedObject.value.type === 'text';
});

// 初始化画布
onMounted(async () => {
  await nextTick();
  canvas = new fabric.Canvas(fabricCanvas.value, {
    width: 800,
    height: 600,
    backgroundColor: '#ffffff'
  });
  
  // 设置选择事件
  canvas.on('selection:created', handleObjectSelected);
  canvas.on('selection:updated', handleObjectSelected);
  canvas.on('selection:cleared', handleSelectionCleared);
  
  // 设置对象修改事件
  canvas.on('object:modified', updateSelectedObjectProps);
});

onUnmounted(() => {
  if (canvas) {
    canvas.dispose();
  }
});

// 处理选择事件
function handleObjectSelected(e) {
  selectedObject.value = canvas.getActiveObject();
}

function handleSelectionCleared() {
  selectedObject.value = null;
}

function updateSelectedObjectProps() {
  // 当选中对象被修改时更新属性
  // 这里不需要做什么，因为我们的属性面板组件会直接从selectedObject获取最新属性
}

// 处理元素添加
function handleAddElement(type) {
  switch (type) {
    case 'text':
      addText();
      break;
    case 'rectangle':
      addRectangle();
      break;
    case 'circle':
      addCircle();
      break;
    case 'triangle':
      addTriangle();
      break;
    case 'polygon':
      addPolygon();
      break;
    case 'brush':
      toggleBrush();
      break;
    case 'line':
      addLine();
      break;
  }
}

// 添加文本
function addText() {
  const text = new fabric.IText('输入文字', {
    left: 100,
    top: 100,
    fontFamily: 'Arial',
    fontSize: 24,
    fill: selectedColor.value
  });
  
  canvas.add(text);
  canvas.setActiveObject(text);
}

// 添加矩形
function addRectangle() {
  const rect = new fabric.Rect({
    left: 100,
    top: 100,
    width: 100,
    height: 100,
    fill: selectedColor.value,
    stroke: '#000000',
    strokeWidth: 1
  });
  
  canvas.add(rect);
  canvas.setActiveObject(rect);
}

// 添加圆形
function addCircle() {
  const circle = new fabric.Circle({
    left: 100,
    top: 100,
    radius: 50,
    fill: selectedColor.value,
    stroke: '#000000',
    strokeWidth: 1
  });
  
  canvas.add(circle);
  canvas.setActiveObject(circle);
}

// 添加三角形
function addTriangle() {
  const triangle = new fabric.Triangle({
    left: 100,
    top: 100,
    width: 100,
    height: 100,
    fill: selectedColor.value,
    stroke: '#000000',
    strokeWidth: 1
  });
  
  canvas.add(triangle);
  canvas.setActiveObject(triangle);
}

// 添加多边形
function addPolygon() {
  const polygon = new fabric.Polygon([
    { x: 50, y: 0 },
    { x: 100, y: 25 },
    { x: 100, y: 75 },
    { x: 50, y: 100 },
    { x: 0, y: 75 },
    { x: 0, y: 25 }
  ], {
    left: 100,
    top: 100,
    fill: selectedColor.value,
    stroke: '#000000',
    strokeWidth: 1
  });
  
  canvas.add(polygon);
  canvas.setActiveObject(polygon);
}

// 添加线条
function addLine() {
  const line = new fabric.Line([50, 50, 200, 200], {
    stroke: selectedColor.value,
    strokeWidth: 2
  });
  
  canvas.add(line);
  canvas.setActiveObject(line);
}

// 切换画笔模式
function toggleBrush() {
  canvas.isDrawingMode = !canvas.isDrawingMode;
  if (canvas.isDrawingMode) {
    canvas.freeDrawingBrush.color = selectedColor.value;
    canvas.freeDrawingBrush.width = 5;
  }
}

// 设置颜色
function setColor(color) {
  selectedColor.value = color;
  
  if (canvas.isDrawingMode) {
    canvas.freeDrawingBrush.color = color;
  }
  
  if (selectedObject.value) {
    selectedObject.value.set('fill', color);
    canvas.renderAll();
  }
}

// 添加素材
function addMaterial(material) {
  fabric.loadSVGFromURL(material.url, function(objects, options) {
    const loadedObject = fabric.util.groupSVGElements(objects, options);
    loadedObject.set({
      left: 100,
      top: 100,
      scaleX: 0.5,
      scaleY: 0.5
    });
    
    canvas.add(loadedObject);
    canvas.setActiveObject(loadedObject);
  });
}

// 网格和标尺功能
function toggleGrid() {
  console.log('Toggle grid');
  // 实现网格切换
}

function toggleRuler() {
  console.log('Toggle ruler');
  // 实现标尺切换
}

// 更新对象属性
function updateObjectProperty(property, value) {
  if (!selectedObject.value) return;
  
  if (property === 'width') {
    selectedObject.value.set('scaleX', value / selectedObject.value.width);
  } else if (property === 'height') {
    selectedObject.value.set('scaleY', value / selectedObject.value.height);
  } else {
    selectedObject.value.set(property, value);
  }
  
  canvas.renderAll();
}

// 切换文本样式
function toggleTextStyle(property, value) {
  if (!selectedObject.value || !isTextObject.value) return;
  
  const currentValue = selectedObject.value[property];
  const newValue = currentValue === value ? (property === 'fontWeight' ? 'normal' : (property === 'fontStyle' ? 'normal' : false)) : value;
  
  selectedObject.value.set(property, newValue);
  canvas.renderAll();
}

// 对象操作
function copySelected() {
  if (!selectedObject.value) return;
  
  selectedObject.value.clone(function(cloned) {
    cloned.set({
      left: cloned.left + 20,
      top: cloned.top + 20
    });
    
    canvas.add(cloned);
    canvas.setActiveObject(cloned);
  });
}

function deleteSelected() {
  if (!selectedObject.value) return;
  
  canvas.remove(selectedObject.value);
  selectedObject.value = null;
}

function moveToTop() {
  if (!selectedObject.value) return;
  selectedObject.value.bringToFront();
  canvas.renderAll();
}

function moveToBottom() {
  if (!selectedObject.value) return;
  selectedObject.value.sendToBack();
  canvas.renderAll();
}

// 画布操作
function saveDesign() {
  const json = canvas.toJSON();
  console.log('Design saved:', JSON.stringify(json));
  // 在实际应用中，这里会保存到后端
}

function exportDesign() {
  const dataURL = canvas.toDataURL({
    format: 'png',
    quality: 1
  });
  
  const link = document.createElement('a');
  link.href = dataURL;
  link.download = 'design.png';
  link.click();
}

function previewDesign() {
  const dataURL = canvas.toDataURL();
  window.open(dataURL);
}
</script>

<style scoped>
.design-editor-container {
  height: calc(100vh - 60px); /* 根据顶部导航栏的高度调整 */
  display: flex;
  flex-direction: column;
}

.editor-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧侧边栏 */
.editor-sidebar {
  width: 220px;
  border-right: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  overflow-y: auto;
}

/* 中间画布区域 */
.editor-canvas-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #e9e9e9;
}

.editor-toolbar {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
}

.canvas-container {
  flex: 1;
  overflow: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.fabric-canvas {
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

/* 右侧属性面板 */
.editor-properties {
  width: 250px;
  border-left: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.properties-header {
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.properties-header h3 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.properties-content {
  flex: 1;
  overflow-y: auto;
}

.no-selection-hint {
  padding: 20px;
  color: #999;
  text-align: center;
}
</style>